<template>
  <div class="login">
    <div class="login_title">工艺数据分析软件</div>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">欢迎登录</h3>
      <el-form-item prop="username">
        <vxe-input v-model="loginForm.username" placeholder="请输入账号" size="medium">
          <template #prefix>
            <i class="vxe-icon-user-fill"></i>
          </template>
        </vxe-input>
      </el-form-item>
      <el-form-item prop="password">
        <vxe-input
          size="medium"
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          @keyup.enter.native="handleLogin"
        >
          <template #prefix>
            <i class="vxe-icon-lock-fill"></i>
          </template>
        </vxe-input>
      </el-form-item>
      <!-- <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item> -->

      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width: 100%"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right" v-if="register">
          <router-link class="link-type" :to="'/register'"
            >立即注册</router-link
          >
        </div>
      </el-form-item>

      <div
        style="display: flex; justify-content: space-between; font-size: 14px"
      >
        <el-link type="primary" @click="forgetPassword">忘记密码</el-link>
        <div style="display: flex">
          <span style="color: #606266">还没有账号？</span>

          <router-link class="link-type" :to="'/register'"
            >立即注册</router-link
          >
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { aesEncrypt, aesDecrypt } from "@/utils/crypto";

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "admin",
        password: "admin",
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        //  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
      email: ''
    },
  },
  created() {
    this.getEmail()
    // this.getCode();
    // this.getCookie();
  },
  methods: {
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getEmail() {
      this.$http({
        url: "/dict/email",
        method: "get",
      }).then(({ data }) => {
        this.email = data.data
      })
    },
    forgetPassword() {
      if (!this.loginForm.username) {
        this.$message({
          message: "请输入您的账号",
          type: "warning",
        });
        return;
      }
      this.$alert(`<p>请联系管理员重置密码</p><p>联系方式：${this.email}</p>`, '提示',  {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
      })
      this.$http({
        url: "/user/forgetPassword",
        method: "get",
        params: {
          userAccount: this.loginForm.username
        }
      }).then(({ data }) => {
        console.log(data)
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : aesDecrypt(password),
      };
    },
    handleLogin() {
const newPwd = aesEncrypt(this.loginForm.password)

      // const newPwd = btoa(this.loginForm.password)
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$store.dispatch('tagsView/delAllViews');
          this.$store.commit("SET_ROLES", []);
          this.loading = true;
          this.loading = false;
          this.$router.push({ path: this.redirect || "/" }).catch(() => {});
          this.$http({
            url: "/login/login",
            method: "post",
            data: {
              userName : this.loginForm.username,
              password : newPwd
            },
          })
            .then(({ data }) => {
              console.log(data);
              if(data.code == 1000){
                this.$message.error(data.msg)
                return
              }
              localStorage.setItem("loginTime", new Date().getTime())
              // 这里走路由
              this.$http({
                url: "/menu/userMenu",
                methods: "get",
              }).then(({ data }) => {

               sessionStorage.setItem('menu', JSON.stringify(data.data.pc))
              })
              this.$store.commit("SET_TOKEN", data.data.token);
              localStorage.setItem("token", data.data.token);
              localStorage.setItem("user", JSON.stringify(data.data));
              this.$message.success("登录成功");
              this.$router.push("/");
              // this.$router.push({ path: this.redirect || "/" }).catch(() => { });
            })
            .catch((err) => {
              // this.loading = false;
              // this.$message.error(err.msg);
            })
            .then(({ data }) => {
              this.$store.commit("SET_TOKEN", data.data.token);
              localStorage.setItem("token", JSON.stringify(data.data.token));
              console.log(data);
              this.$message.success("登录成功");
              this.$router.push({ path: this.redirect || "/" }).catch(() => {});
            })
            .catch(() => {
              this.loading = false;
            });
          // this.$store.dispatch("Login", this.loginForm).then(() => {
          //   this.$router.push({ path: this.redirect || "/" }).catch(() => { });
          // }).catch(() => {
          //   this.loading = false;
          //   if (this.captchaEnabled) {
          //     this.getCode();
          //   }
          // });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep {
  .vxe-input{
    width: 100%;
  }
  .vxe-input.size--medium {
    font-size: 14px;
    height: 36px;
    line-height: 36px;
  }
}
.login {
  height: 100%;
  width: 100%;
  background-image: url("../assets/images/login_bg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: fixed;
  .login_title {
    margin: 50px auto auto 50px;
    color: #1c2126;
    font-weight: 550;
    font-size: 32px;
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #1c2126;
  font-weight: 550;
}

.login-form {
  border-radius: 6px;
  background: rgb(255, 255, 255, 0.7);
  width: 400px;
  padding: 25px;
  margin-left: 60%;
  margin-top: 12%;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
</style>
